#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    int minFlips(vector<vector<int>>& grid) {
        int n = grid.size();
        int m = grid[0].size();
        int res = 0;
        for (int i = 0; i < n / 2; i++)
        {
            for (int j = 0; j < m / 2; j++)
            {
                int zero = 0, one = 0;
                grid[i][j] == 0 ? zero++ : one++;
                grid[n - i - 1][j] == 0 ? zero++ : one++;
                grid[i][m - j - 1] == 0 ? zero++ : one++;
                grid[n - i - 1][m - j - 1] == 0 ? zero++ : one++;
                res += min(4 - one, 4 - zero);
            }
        }
        int total_one = 0;
        int make = 0;
        if (n % 2 == 1 || m % 2 == 1)
        {
            if (n % 2 == 1)
                for (int j = 0; j < m / 2; j++)
                {
                    if (grid[n / 2][j] != grid[n / 2][m - j - 1]) make++;
                    if (grid[n / 2][j] == grid[n / 2][m - j - 1] && grid[n / 2][j] == 1) total_one += 2;
                }

            if (m % 2 == 1)
                for (int i = 0; i < n / 2; i++)
                {
                    if (grid[i][m / 2] != grid[n - i - 1][m / 2]) make++;
                    if (grid[i][m / 2] == grid[n - i - 1][m / 2] && grid[i][m / 2] == 1) total_one += 2;
                }

            if (n % 2 == 1 && m % 2 == 1 && grid[n / 2][m / 2] == 1) res++;

            if (total_one % 4 != 0 && make == 0) res += 2;
            else res += make;
        }
        return res;
    }
};